package com.bckj.fastboot.core.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Slf4j
public class TransactionUtils {

    /**
     * 事物提交后执行
     * @param runnable 禁止实现耗时操作/事物操作，常用于发送异步消息
     */
    public static void afterCommit(Runnable runnable) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    try {
                        runnable.run();
                    } catch (Exception e) {
                        log.error("Exception occurred while executing runnable after commit.", e);
                    }
                }
            });
        } else {
            log.warn("Transaction is not active. Executing runnable immediately without transactional context.");
            try {
                // 在非事务环境下执行Runnable，注意这里捕获并记录了异常
                runnable.run();
            } catch (Exception e) {
                log.error("Exception occurred while executing runnable outside of a transaction.", e);
            }
        }
    }
}
